package net.ptcs.litang.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.ptcs.litang.entity.CertType;
import net.ptcs.litang.entity.City;
import net.ptcs.litang.entity.UserType;
import net.ptcs.litang.entity.Users;
import net.ptcs.litang.service.ProvinceService;
import net.ptcs.litang.service.UserService;
import net.ptcs.litang.util.Md5Utils;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet(description = "", urlPatterns = { "/AdminUserServlet" })
public class AdminUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//1.获取数据
				String username=request.getParameter("username"); //用户名
				String password=request.getParameter("password"); //密码
				String authority=request.getParameter("authority"); //权限
				String confirm_password=request.getParameter("confirm_password"); //确认密码
				String real_name = request.getParameter("real_name");//真实姓名
				String sex=request.getParameter("sex");//性别
				String province = request.getParameter("province");//省份
				String city = request.getParameter("city");//城市
				String cert_type = request.getParameter("cert_type");//证件类型
				String cert = request.getParameter("cert");//证件号码
				String birthday_date=request.getParameter("birthday");//出生日期
				String user_type = request.getParameter("user_type");//旅客类型
				String content = request.getParameter("content");//备注
				StringBuffer sb = validateRegisterForm(username, password, confirm_password, "选中了");
				
				if(sb.length() > 0) {
					request.setAttribute("message", "必填信息为空，请重新注册");
					request.getRequestDispatcher("/ToAddUserServlet").forward(request, response);
				}else {
					Date birthday=null;
					try {
						birthday=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("birthday"));
					} catch (Exception e) {
						e.printStackTrace();
					}
					UserService userService=UserService.getInstance();
					Users user = new Users();
					user.setUsername(username);//用户名
					user.setPassword(Md5Utils.md5(password));//密码
					
					user.setRule(authority.equals("管理员")?"1":"2");//用户类型 2为普通用户
					user.setRealname(real_name);//真实姓名
					user.setSex(sex.charAt(0));//性别 String 转 Character
					
					City c = new City();
					c.setCityId(city);
					user.setCity(c);//获取城市 String 转 引用类型
					
					user.setCerttype(new CertType(Integer.parseInt(cert_type), null));//证件类型 String 转 引用类型
					
					user.setCert(cert);//证件号码
					
					
					try {
						user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday_date));
					} catch (ParseException e) {
						e.printStackTrace();
					}//出身日期 String 转 date
					
					user.setUsertype(new UserType(Integer.parseInt(user_type), null));//旅客类型 String 转 引用类型
					user.setContent(content);//备注
					user.setLoginIp(request.getRemoteAddr());//设置IP
					
					if(userService.register(user))
					{
						response.sendRedirect("/ToQueryUserServlet");
						
						//response.sendRedirect(request.getContextPath()+"/login.jsp");//request.getContextPath()===/litang_user_register
					}else
					{
//						System.out.println("register fail");
						//注册失败，回到注册页面
						request.setAttribute("message", "注册失败");
						//request.getRequestDispatcher("/user_register.jsp").forward(request, response);
						request.getRequestDispatcher("/ToAddUserServlet").forward(request, response);
					}
				}
	}
	
       
	/**
	 * 对表单进行服务端校验的方法 
	 * @param username
	 * @param password
	 * @param confirm_password
	 * @return 
	 */
	private StringBuffer validateRegisterForm(String username, String password,String confirm_password,String agree) {
		StringBuffer validate_message=new StringBuffer();
		if(username==null||"".equals(username))
		{
			validate_message.append("用户名为空");
		}
		if(password==null||"".equals(password)||confirm_password==null||"".equals(confirm_password))
		{
			validate_message.append("密码或者确认密码为空");
		}
		if(!password.equals(confirm_password))
		{
			validate_message.append("两次密码输入不一致");
		}
		if(agree == null) {
			validate_message.append("请阅读《理塘铁路客户服务中心网站服务条款》并勾选");
		}
		if(validate_message.length()>0)
		{
			System.out.println(validate_message.toString());
			return validate_message;
		}
		return validate_message;
	}
}
